// components/order/list.js
import {
  cancel,
  reminder,
  find,
  received,
  payment,
  del,
  temporaryStorage,
  checkOpenBusinessView,
  queryShippingStatus
} from '../../api/order.js';
import {
  submit,
  query
} from '../../api/payment';
import {
  buyForOrder
} from '../../api/cart'
const util = require('../../utils/util.js')
let app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    orderData: {
      type: Object,
      value: null,
      sn: '',
    },
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      this.data.orderData.subPrice = this.data.orderData.subPrice.toFixed(2)
      this.setData({
        orderData: this.data.orderData
      })
      this.getOnlinePayment()
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    img: 'https://icweiliimg1.pstatp.com/weili/l/540018848208912837.webp',
    extractCodeType: false,
    onlinePayment: '',
    yunchang: app.globalData.yunchang
  },
  /**
   * 组件的方法列表
   */
  methods: {
    temporaryStorageClick(data) {
      // console.log(data.currentTarget.dataset.id);
      var _this = this
      let params = {}
      params.orderId = data.currentTarget.dataset.id
      wx.showModal({
        title: '提示',
        content: '确认暂存云仓?',
        success(res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            temporaryStorage(params).then(res => {
              wx.showToast({
                title: '加入成功',
                icon: 'success',
              })
              _this.triggerEvent('refresh')
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    getOnlinePayment() {
      this.data.onlinePayment = app.globalData.onlinePayment
      this.setData({
        onlinePayment: app.globalData.onlinePayment,
      })
      console.log(this.data.onlinePayment, "222222222222222222222222222222222")
    },
    refundsclick() {
      wx.navigateTo({
        url: '/pages/order/jumpPage/order/refund?id=' + this.data.orderData.id,
      })
    },
    detailsClick() {
      wx.navigateTo({
        url: '/pages/order/jumpPage/order/details?id=' + this.data.orderData.id,
      })
    },
    cancelOrder(data) { // 取消订单
      console.log(data)
      var _this = this
      wx.showModal({
        title: '确认取消订单？',
        content: '取消后可在已关闭订单再次购买',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            _this.loadCancel(data.currentTarget.dataset.id)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    loadCancel(data) {
      var _this = this
      console.log(data)
      cancel(data).then(
        res => {
          console.log(res)
          if (res.type == 'success') {
            wx.showToast({
              title: res.content,
            })
            _this.refresh()
          }
        }
      ).catch(error => {
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    },
    refund(data) { // 退款
      wx: wx.navigateTo({
        url: '/pages/order/jumpPage/order/refund?id=' + this.data.orderData.id,
      })
    },
    remindShipping(data) { // 提醒发货
      console.log(data)
      var _this = this
      reminder(_this.data.orderData.id).then(
        res => {
          console.log(res)
          if (res.type == 'success') {
            wx.showToast({
              title: res.content,
            })
          }
        }
      ).catch(error => {
        wx.showToast({
          title: error.content,
          icon: "none",
        })
      })
    },
    lookLogistics(data) { // 查看物流
      wx.navigateTo({
        url: '/pages/member/logistics/list?id=' + this.data.orderData.id,
      })
    },
    confirmReceipt(data) { // 确认收货
      var _this = this
      wx.showLoading({
        title: '加载中'
      })
      checkOpenBusinessView({ orderId: _this.data.orderData.id }).then(res => {
        if (!util.isNull(res.data)) {
          wx.hideLoading()
          if (wx.openBusinessView) {
            wx.openBusinessView({
              businessType: 'weappOrderConfirm',
              extraData: {
                merchant_id: res.data.merchant_id,
                merchant_trade_no: res.data.merchant_trade_no,
                transaction_id: res.data.transaction_id
              },
              success() {
                queryShippingStatus({ orderId: _this.data.orderData.id }).then(shippingRes => {
                  if (shippingRes.data) {
                    received(_this.data.orderData.id).then(response => {
                      console.log(response)
                      if (response.type == 'success') {
                        wx.showToast({
                          title: response.content,
                        })
                        _this.refresh()
                      }
                    }
                    ).catch(error => {
                      console.log(error)
                    })
                  }
                })
              },
              fail(err) {
                wx.showToast({
                  title: err.errMsg,
                  icon: 'none'
                })
              }
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '微信版本过低，请升级',
            })
          }
        } else {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '是否确认收货！',
            success(res) {
              if (res.confirm) {
                received(_this.data.orderData.id).then(
                  res => {
                    console.log(res)
                    if (res.type == 'success') {
                      wx.showToast({
                        title: res.content,
                      })
                      _this.refresh()
                    }
                  }
                ).catch(error => {
                  console.log(error)
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      })
    },


    confirmClick() {
      wx.navigateTo({
        url: '/pages/order/jumpPage/order/confirm',
      })
    },
    again() { // 再次购买
      var _this = this
      var product = this.data.orderData.itemList[0]
      let data = {}
      data.orderId = product.orderId
      data.uuid = app.globalData.uuid
      buyForOrder(data).then(
        res => {
          if (res.type == 'success') {
            wx.navigateTo({
              url: '/pages/goods/submit/index',
            })
          }
        }
      ).catch(error => {
        wx.showToast({
          title: '服务器开小差了，请重新点击购买',
          icon: 'none',
          duration: 2000
        })
      })
    },
    evaluate(data) { // 评价
      console.log(data)
      wx.navigateTo({
        url: '/pages/order/jumpPage/order/evaluation?id=' + this.data.orderData.id,
      })
    },
    refresh() {
      this.triggerEvent('refresh')
    },
    delClick() {
      var _this = this
      wx.showModal({
        title: '提示',
        content: '是否确认删除！',
        success(res) {
          if (res.confirm) {
            del(_this.data.orderData.id).then(
              res => {
                if (res.type == 'success') {
                  _this.refresh()
                }
              }
            ).catch(error => {
              console.log(error)
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    paymentClick() { // 付款
      var _this = this
      payment(_this.data.orderData.id).then(res => {
        if (res.type == 'success') {
          console.log(res)
          if (res.data.paymentPluginId == 'facePayPlugin') {
            wx.navigateTo({
              url: '/pages/member/share/determinePage/qRCodePayment?id=' + res.data.id,
            })
          } else {
            if (res.data.way != 2) {
              _this.submitClick(res)
            } else {
              console.log({
                sn: res.data.sn,
                userId: app.globalData.uuid,
                token: app.globalData.token,
                mchName: app.globalData.mchName,
                amount: res.data.amount,
                createDate: res.data.createDate,
                // itemList: data.data.itemList,
                address: this.data.orderData.address,
                consignee:this.data.orderData.consignee,
                phone: this.data.orderData.phone,
                memo: res.data.memo,
                firstEnter: true
              });
            _this.data.sn = res.data.sn
            wx.showLoading({
              title: '等待支付',
            })
            wx.openEmbeddedMiniProgram({
              appId: 'wx2d00e086c8d08008',
              path: `pages/payment/payment`,
              // envVersion: 'trial',
              extraData: {
                sn: res.data.sn,
                userId: app.globalData.uuid,
                token: app.globalData.token,
                mchName: app.globalData.mchName,
                amount: res.data.amount,
                createDate: res.data.createDate,
                // itemList: data.data.itemList,
                address: this.data.orderData.address,
                consignee:this.data.orderData.consignee,
                phone: this.data.orderData.phone,
                memo: res.data.memo,
                firstEnter: true
              },
              fail: (fail) => {
                wx.hideLoading()
                wx.showModal({
                  title: '支付失败',
                  content: '拉起支付失败，请点击 "允许" 跳转支付',
                  showCancel: false
                })
                this.data.shippingClickFlag = true //开启防双击
              }
            })
            }
          }
        } else {
          wx.showToast({
            icon: "none",
            title: '支付失败',
          })
        }
      }).catch(error => {
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    },
    submitClick(data) {
      var _this = this
      _this.data.sn = data.data.sn
      wx.showLoading({
        title: '加载中...',
      })
      submit({
        paymentPluginId: 'weixinMiniPayPlugin',
        sn: data.data.sn
      }).then(res => {
        console.log(res)
        wx.hideLoading()
        if (res.type == 'success') {
          wx.requestPayment({
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': res.data.signType,
            'paySign': res.data.paySign,
            'success': function (red) {
              _this.queryClick()
            },
            'fail': function (red) {
              console.log(red);
            }
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '支付失败',
          })
        }
      }).catch(error => {
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    },
    queryClick() {
      var _this = this
      query({
        sn: _this.data.sn
      }).then(res => {
        console.log(res)
        if (res.type == 'success') {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                _this.refresh()
              }, 1500)
            }
          })
        } else {
          _this.refresh()
        }
      }).catch(error => {
        wx.showToast({
          icon: "none",
          title: error.content,
        })
      })
    },
    extractCodeClick(data) {
      console.log(data)
      var _this = this
      this.data.extractCodeType = !this.data.extractCodeType
      this.setData({
        extractCodeType: this.data.extractCodeType
      })
      var id = data.currentTarget.dataset.id
      _this.selectComponent("#extract").qrcodeClick(id);
    },
    cancelClick() {
      this.data.extractCodeType = !this.data.extractCodeType
      this.setData({
        extractCodeType: this.data.extractCodeType
      })
    }
  }
})
